/**
 * 
 */
package atom.core2.j2ee.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;

import atom.core0.exception.BizSysException;
import atom.core0.j2ee.page.Page;
import atom.core0.j2ee.page.PageResult;





/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2010
 * </p>
 * <p>
 * </p>
 * 
 * @author 赵明财
 * @version 1.0
 */
public class RequestManager
{
	/**
	 * Log4J Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(RequestManager.class);
	protected static final String GBK_TEXT_HTML = "text/html;charset=GBK";
	//一、分页
	//分页传入参数
	public static final String PAGE_SIZE = "pageSize";
	public static final String PAGE_NUMBER = "pageNumber";
	
	//分页传出参数
	public static final String PAGE_RESULT = "pageResult";

	//二、用户权限菜单
	//顶部菜单
	public static final String BUTTON_MENUS = "button_menus";
	//菜单级别 模块代码
	public static final String MODULE_CODE ="MODULE_CODE";
	//导航信息
	public static final String PRIVILEGE_PATH = "PRIVILEGE_PATH";
	
	//三、JSP TAG控件参数
	//新增/修改　成功失败对话框的消息
	//<f:msg styleClass="msg"/> 
	public static final String MSG = "msg";


	
	

	//四、传出参数
	public static final String SESSION_INFO = "session_info";
	
	public static final String INFO = "info";//InfoView类


	
	public static final int DEFAULT_PAGE_SIZE = 20;










	/*
	 * 写入查询结果对象到request中
	 */



	static public void setPaginater(HttpServletRequest request, PageResult p) 
	{
		request.setAttribute(RequestManager.PAGE_RESULT, p);
		request.setAttribute("list", p.getData());
	}




	/**
	 * 获取分页参数
	 * 
	 * @param request
	 * @return
	 */
	static public Page getPage(HttpServletRequest request) {
		return new Page(getPageNumber(request), getPageSize(request));

	}
	/**
	 * 获取每页笔数
	 * @param request
	 * @return
	 */
	static public  int getPageSize(HttpServletRequest request) {
		String pageSize = request.getParameter(PAGE_SIZE);
		
		return NumberUtils.isDigits(pageSize) ? Integer.parseInt(pageSize) : DEFAULT_PAGE_SIZE;
	}
	
	/**
	 * 取页数.
	 * @param request
	 * @return
	 */
	static public  int getPageNumber(HttpServletRequest request) {
		String pageNumber = request.getParameter(PAGE_NUMBER);
		
		return NumberUtils.isDigits(pageNumber) ? Integer.parseInt(pageNumber) : 1;
	}
	
	//以下是令牌环的代码

	/**
	 * response 输出消息.
	 *
	 * @param response
	 * @param msg
	 * @return
	 */
	static protected void respond(final HttpServletResponse response, final String msg) {
		PrintWriter writer = null;

		try {
			response.setContentType(GBK_TEXT_HTML);
			writer = response.getWriter();
			writer.write(msg == null ? "" : msg);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(writer);
		}

		return ;
	}
	//后台跳转到一个页面 然后页面跳转，相当于前台跳转（带post参数）
	public static void forward(HttpServletRequest request,HttpServletResponse response,String url) throws IOException,ServletException
	{
		RequestDispatcher rd = request.getSession().getServletContext().getRequestDispatcher(url);
		rd.forward(request, response);
		
	}
	//直接前台跳转（无post参数）
	public static void redirect(HttpServletResponse response,String url) throws Exception
	{
		logger.debug("redirect跳转到["+ url +"]页面");
		response.sendRedirect(url);
	}

	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	public static String getRemoteInfo(HttpServletRequest request)
	{
		String info="";
		try
		{
			if (request.getRemoteHost()!=null)
				info+=request.getRemoteHost();
		}
		catch(Exception e)
		{
		}

		try
		{
			if (request.getRemoteAddr()!=null)
				info+=request.getRemoteAddr();
		}
		catch(Exception e)
		{
		}
		return info;
		
	}
	public static void returnTextMsg(HttpServletResponse response, String textmsg,String charset) 
	{
		PrintWriter out = null;
		try
		{
			response.setContentType("text/plain");
			response.setCharacterEncoding(charset);
			out = response.getWriter();
			out.print(textmsg);
			out.flush();
		}
		catch (Exception e)
		{
			logger.error(e.getMessage(),e);
		}
		finally
		{
			if (out != null)
				out.close();

		}
	}
	//客户端使用时 方法如下
	//<img src="<%=request.getContextPath()%>/enterprise.do?method=showEntpPhoto"/>
	public void showImg(HttpServletRequest request,HttpServletResponse response,byte[] bt)throws BizSysException
	{
		try
		{
			if (bt == null || bt.length == 0)
			{
				String path = request.getRealPath("/") + "images/no_p.png";
				File file = new File(path);
				InputStream in = new FileInputStream(file);
				OutputStream os = response.getOutputStream();
				byte[] b = new byte[1024];
				int len = 0;
				while ((len = in.read(b)) != -1)
				{
					os.write(b, 0, len);
				}
				os.close();
				in.close();
			}
			else
			{
				response.setContentType("images/jpeg");
				OutputStream os = response.getOutputStream();
				os.write(bt);
				os.close();
			}
		}
		catch (Exception e)
		{
			throw new BizSysException(e);
		}
	}
	
	//请求的是http://127.0.0.1:5050/hessian/myhessian/hsdemo.do?method=aa
	//下面是各个函数返回的结果
	//       http://127.0.0.1:5050/hessian/myhessian/hsdemo.do
	public static String getURL(HttpServletRequest request)
	{
		return request.getRequestURL().toString();
	}
	//       /hessian/myhessian/hsdemo.do
	public static String getURI(HttpServletRequest request)
	{
		return request.getRequestURI();
		
	}	    
	//       /hessian/myhessian/hsdemo.do?method=add
	public static String getResourceURI(HttpServletRequest request)
	{
		return WebResource.getURI(request);
		
	}	
	//       /hessian
	public static String getContext(HttpServletRequest request)
	{
		return request.getContextPath();
		
	}	
	//       http://127.0.0.1:5050/hessian
	public static String getBasePath(HttpServletRequest request)
	{
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		return basePath;
	}	
	//       /hsdemo.do
	public static String getActionName(HttpServletRequest request)
	{
		String[] a=request.getRequestURI().split("/");
		return "/"+a[a.length-1];
	}
	
	
}
